import { defineStore } from "pinia";
import { ref } from "vue";
import { computed } from "vue";
import { useUserStore } from "./user";
import { addCartList, getCartList,delCartList } from "@/apis/Cart";
export const useCartStore = defineStore(
  "cart",
  () => {
    const cartList = ref([]);
    //添加购物车
    const userStore = useUserStore();
    const isLogin = computed(() => userStore.userInfo.token)
    const cartAdd = async (obj) => {
      const { skuId, count } = obj;
      if (isLogin.value) {
        await addCartList(skuId, count);
        getCart()
      } else {
        const item = cartList.value.find((item) => item.skuId === obj.skuId);
        if (item) {
          item.count += obj.count;
        } else {
          cartList.value.push(obj);
        }
      }
    };
    //删除购物车
    const cartRemove = async (skuId) => {
     if(isLogin.value){
      await delCartList([skuId])
      getCart()
     }else{
      cartList.value = cartList.value.filter((item) => item.skuId !== skuId);
     }
    };
    //获取购物车列表
    const getCart = async () => {
      const { data } = await getCartList();
      cartList.value = data.result;
    }
    //更改商品选中状态
    const changeSelected = (skuId, selected) => {
      const item = cartList.value.find((item) => {
        return item.skuId === skuId;
      });
      item.selected = selected;
    };
    //商品全选
    const selectAll = (selected) => {
      cartList.value.forEach((item) => (item.selected = selected));
    };
    //清空购物车数据
    const clearCartList = () => {
      cartList.value = []
    }
    //获取商品总数
    const allCount = computed(() => {
      return cartList.value.reduce((acc, curr) => {
        return acc + curr.count;
      }, 0);
    });
    //获取商品总价
    const allPirce = computed(() => {
      return cartList.value.reduce((acc, curr) => {
        return acc + curr.count * curr.price;
      }, 0);
    });
    //商品是否全选
    const isAllCheck = computed(() => {
      return cartList.value.every((item) => item.selected === true);
    });
    //已选商品价格
    const checkPrice = computed(() => {
      return cartList.value.reduce((acc, curr) => {
        if (curr.selected) {
          return acc + curr.count * curr.price;
        }
        return acc;
      }, 0);
    });
    //已选商品数量
    const checkCount = computed(() => {
      return cartList.value.reduce((acc, curr) => {
        if (curr.selected) {
          return acc + curr.count;
        } else {
          return acc;
        }
      }, 0);
    });
    return {
      cartList,
      allCount,
      allPirce,
      isAllCheck,
      checkCount,
      checkPrice,
      selectAll,
      changeSelected,
      cartAdd,
      cartRemove,
      clearCartList,
      getCart
    };
  },
  {
    persist: true,
  }
);
